package com.example.test.advice.第三章_类_对象_方法.建议46_equals应该考虑null值情景;

import java.util.ArrayList;
import java.util.List;

public class EqualsDemo {

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        Person p1 = new Person("张三");
        Person p2 = new Person(null);
        personList.add(p1);
        personList.add(p2);
        System.out.println("列表中是否包含张三："+ personList.contains(p1));//true
        System.out.println("列表中是否包含张三："+personList.contains(p2));//true
    }
}

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //违反了对称性原则：如果x.equqls(y)，那么y.equqals(x)也应该返回true
   /* @Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            Person p = (Person) o;
            return name.equalsIgnoreCase(p.getName().trim());
        }
        return false;
    }*/

    //改进
    @Override
    public boolean equals(Object o) {
        if(this ==o){
            return true;
        }
        if (o instanceof Person) {
            Person p = (Person) o;
            if(p.getName() == null || name == null){
                return false;
            }else {
                return name.equalsIgnoreCase(p.getName());
            }
        }
        return false;
    }

}